﻿using System;
using System.Web;


namespace Wayloop.Blog.DependencyResolution
{
    public class DependencyModule : IHttpModule
    {
        private static readonly object FauxLock = new object();
        private static bool isInitialized;


        /// <summary>
        /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
        /// </summary>
        public void Dispose()
        {
        }


        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnContextBeginRequest;
        }


        private void OnContextBeginRequest(object sender, EventArgs e)
        {
            RegisterDependencies();
        }


        private void RegisterDependencies()
        {
            if (!isInitialized) {
                lock (FauxLock) {
                    if (!isInitialized) {
                        DependencyRegistry.Initialize();
                        isInitialized = true;
                    }
                }
            }
        }
    }
}